#include "../main.h"

#define PATH_FIFO "/home/yujiu/fifo"

int main()
{
    int res=0;
    res=access(PATH_FIFO,F_OK);
    if(res==-1){
        perror("access");
        exit(EXIT_FAILURE);
    }
    int fd=open(PATH_FIFO,O_RDONLY);
    if(-1==fd){
        perror("open");
        exit(EXIT_FAILURE);
    }
    char buf[128];
    ssize_t byte =0;
    struct timeval timeout,timeout_sck;
    timeout.tv_sec=5;
    timeout.tv_usec=0;
    fd_set readfds,readfds_sck;
    FD_ZERO(&readfds);
    FD_SET(fd,&readfds);
    FD_SET(0,&readfds);
    while(1){
        timeout_sck=timeout;
        readfds_sck=readfds;
        res=select(fd+1,&readfds_sck,NULL,NULL,&timeout_sck);
        if(res==-1){
            perror("select");
            close(fd);
            exit(EXIT_FAILURE);
        }else if(0==res){
            printf("timeout\n");
        }else{
            for(int i=0;i<res;i++){
                if(FD_ISSET(fd,&readfds_sck)){
                    memset(buf,0,sizeof(buf));
                    byte=read(fd,buf,sizeof(buf));
                    printf("read:%s\n",buf);
                    if(strncmp(buf,"exit",4)==0){
                        close(fd);
                        exit(EXIT_SUCCESS);
                    }
                }
                if(FD_ISSET(0,&readfds_sck)){
                    memset(buf,0,sizeof(buf));
                    fgets(buf,sizeof(buf),stdin);
                    buf[strlen(buf)-1]='\0';
                    printf("read:%s\n",buf);
                    if(strncmp(buf,"exit",4)==0){
                        close(fd);
                        exit(EXIT_SUCCESS);
                    }
                }
            }
        }
    }
    close(fd);
    return 0;
}

